import os
import json
import requests
from wxpy import *
import yaml
from redis import StrictRedis, ConnectionPool

# from pydub import AudioSegment

CONF_PATH = os.path.join(os.path.dirname(__file__), 'conf')
IMG_PATH = os.path.join(os.path.dirname(__file__), 'imgs')
Cache_Path = os.path.join(CONF_PATH, 'wxpy.pkl')


# 服务器配置数据
def init_config(CONF_PATH):
    file_data = ''
    CONF_PATH = os.path.join(CONF_PATH, 'conf.yaml')
    with open(CONF_PATH, 'r', encoding='utf8') as r:
        file_data = r.read()

    config = yaml.load(file_data, Loader=yaml.FullLoader)
    return config


config = init_config(CONF_PATH)
# db_handler=DB_handler(config)

pool = ConnectionPool(host=config['redis']['host'], port=config['redis']['port'], db=config['redis']['db'],
                      password=config['redis']['password'])
rs = StrictRedis(connection_pool=pool)


def init_signature(save_path, token):
    user_name = '老张'
    userid = 'cgai2020'
    url = 'https://openai.weixin.qq.com/openapi/sign/{}'.format(token)
    data = {'user_name': user_name, 'userid': userid}
    head = {"Content-Type": "application/json"}
    respons = requests.post(url, json.dumps(data), headers=head)
    signature = ''
    if respons:
        signature = respons.json()['signature']
        with open(save_path, 'w', encoding='utf8') as w:
            w.write(signature)
    return signature


def get_signature(save_path):
    signature = ''
    with open(save_path, 'r', encoding='utf8') as r:
        signature = r.read()
    return signature


# 微信数据
APPID = 'gAN9RwevbV1fbx4'
TOKEN = 'uEj3814l9YPZFQiNRpu0kymIANqxsu'
EncodingAESKey = 'ue2gZyLMsOK53D5U5VKUL67v4x7zHMekMGbqWSoOBG'
cgai_url = 'https://openai.weixin.qq.com/openapi/aibot/{}'.format(TOKEN)
save_path = os.path.join(CONF_PATH, 'signature')
signature = init_signature(save_path, TOKEN)


def postStart(signature, query, token):
    url = 'https://openai.weixin.qq.com/openapi/aibot/{}'.format(token)
    data = {}
    data['signature'] = signature
    data['query'] = query
    head = {"Content-Type": "application/json"}
    content = requests.post(url, json.dumps(data), headers=head)
    answer = ''
    if content:
        answer = content.json()['answer']

    return answer


bot = Bot(cache_path=Cache_Path, console_qr=True)
bot.enable_puid()
laozhang = bot.friends().search('老张')[0]
by = bot.friends().search('巴音')[0]
g_cgai = bot.groups().search('CGAI')[0]
g_td_manager = bot.groups().search('中国TD社区管理员群')[0]
friends = bot.friends()
mps = bot.mps()


@bot.register(msg_types=FRIENDS)
def auto_accept(msg):
    print('加好友信息', msg.text)
    if '我是' in msg.text.lower():
        new_frient = bot.accept_friend(msg.card)
        new_frient.send('我的小机器助手帮我接受了你的好友请求')


@bot.register(chats=friends, except_self=False)
def get_friend_message(msg):
    mtype = msg.type
    if mtype == 'Text':
        chat = msg.chat
        puid = chat.puid
        nick_name = chat.nick_name
        name = chat.name
        print(puid, nick_name, name)
        print('friend_接到文本')
        print(msg.text)
        # if msg.text.startswith('h') or msg.text.startswith('H'):
        #     print('houdini语音')
        signature = get_signature(save_path)
        answer = postStart(signature, msg.text, TOKEN)
        return answer
    elif mtype == 'Picture':
        print('friend_接到图片')
        pass


    elif mtype == 'Recording':
        # 参考 https://blog.csdn.net/python_lqx/article/details/89763587
        print('friend_接到语音')
        return '个人对话暂时不接受语音，请进入houdini语音助手公众号中进行语音对话'
        # msg_name = msg.file_name
        # msg_file=msg.get_file()
        # print('friend_语音返回内容:',msg_name,type(msg_file))

        # parent_dir = os.path.join(os.path.dirname(__file__), 'recording_tmp')
        # mp3_file_name = msg.file_name
        # # 接收MP3文件并转换为WAV文件
        # bio = BytesIO(msg.get_file())
        # AudioSegment.converter = 'F:\\develop\\ffmpeg\\ffmpeg-win64-static\\bin\\ffmpeg.exe'
        # audio = AudioSegment.from_mp3(bio)
        # wav_file_name = mp3_file_name[:str(mp3_file_name).rindex('.')] + '.wav'
        # print
        # 'recording dir {} wav name {}'.format(parent_dir, wav_file_name)
        # audio.export(os.path.join(parent_dir, wav_file_name), format='wav')
        # # 读取转换后的WAV文件
        # with open(os.path.join(parent_dir, wav_file_name), 'rb') as fp:
        #     voices = fp.read()
        # # 百度语音识别API识别语音信息
        # try:
        #     # 参数dev_pid：1536普通话(支持简单的英文识别)、1537普通话(纯中文识别)、1737英语、1637粤语、1837四川话、1936普通话远场
        #     result = client.asr(voices, 'wav', 16000, {'dev_pid': 1537})
        #     result_text = result["result"][0]
        #     print("receive speech msg: " + result_text)
        # except KeyError:
        #     print("Speech Recognition Error")
    # return '机器助手已收到'


@bot.register(chats=mps, except_self=False)
def get_mp_message(msg):
    """
    公众号千万别自动回复，要不爆炸了
    :param msg:
    :return:
    """
    print(msg.type)
    # chat=g_cgai.chat
    # print(chat.name)
    mtype = msg.type
    if mtype == 'Text' and msg.is_at:
        print('mp接到文本')
        print(msg.text)
        # if msg.text.startswith('h') or msg.text.startswith('H'):
        #     print('houdini语音')
        signature = get_signature(save_path)
        answer = postStart(signature, msg.text, TOKEN)
        return answer

    elif mtype == 'Picture':
        print('mp接到图片')
        return '暂时不能以图操作'

    elif mtype == 'Recording':
        print('mp接到语音')
        msg_name = msg.file_name
        msg_file = msg.get_file()
        print('mp语音返回内容:', msg_name, type(msg_file))
        return '等会去识别语音'
    # return '机器助手已收到'


@bot.register(chats=[g_cgai, g_td_manager], except_self=False)
def get_group_message(msg):  # 现阶段群聊无视图片与语音，个人对话转接语音到公众号
    print(msg.type)
    # friend=friends[0]
    # chat=msg.chat
    # print('chat:',chat)
    # puid=chat.puid
    # print('puid:',puid)
    # nick_name=chat.nick_name
    # print('nick_name:',nick_name)
    # name=chat.name
    # print('name:',name)
    mtype = msg.type
    if mtype == 'Text' and msg.is_at:
        chat = msg.chat
        puid = chat.puid
        nick_name = chat.nick_name  # 这个都是群名
        name = chat.name  # 这个都是群名
        asker = msg.member  # 这才是群里人名
        print(puid, nick_name, asker)
        print('接到文本')
        print(msg.text)
        signature = get_signature(save_path)
        answer = postStart(signature, msg.text, TOKEN)
        print('answer:', answer)
        if msg.text.count('h') > 0 or msg.text.count('H') > 0:
            print('houdini语音')
            q_data = {}
            q_data['m_id'] = str(msg.id)
            q_data['out_id'] = ''
            q_data['module'] = ''
            q_data['asker'] = msg.member.display_name  # 这才是群里人名
            q_data['content'] = msg.text
            q_data['answer'] = ''
            q_data['ha_answer'] = answer
            q_data['label'] = ''
            # print(type(msg.create_time))
            q_data['ask_time'] = msg.create_time.strftime("%Y-%m-%d %H:%M:%S")  # 服务端发送时间

            print('q_data:', q_data)
            # rs.rpush(q_data['m_id'], json.dumps(q_data))
            rs.set(q_data['m_id'],json.dumps(q_data))
            print(rs.keys())
            print('存入rs完成')
        return answer
    elif mtype == 'Picture':
        # print('接到图片')
        # print(msg.picture)
        pass

    elif mtype == 'Recording':
        # print('接到语音')
        # print(msg.recording)
        pass

    # return '机器助手已收到'


# embed()
bot.join()